const path = require('path')
const fs = require('fs')
const http = require('http')
const {URL} = require('url')
const webpack = require('webpack')
const MFC = require('memory-fs')
const webpackConfig = require('@vue/cli-service/webpack.config')
const config = require('../../configure')
const { checkServer } = require('../proxy')


const serverComiler = webpack(webpackConfig)
const mfc = new MFC()
const bundlePath = path.resolve(webpackConfig.output.path, config.serveBundleFileName)
const localFile = path.resolve(config.clientOutpueDir, config.clientManifestFileName)

let url
if (config.rendererPublicPath) {
  url = new URL(
    config.clientManifestFileName,
    config.rendererPublicPath
  ).href
}

const getLocalResources = () => {
  let rawData;
  try {
    rawData = JSON.parse(fs.readFileSync(localFile, 'utf-8'))
  } catch(e) {
    console.error(e)
    rawData = {}
  }

  return rawData
}

const getServerResources = () =>
  new Promise((resolve, reject) => {
    const client = http.get(url, res => {
      let rawData = ''
      res.setEncoding('utf-8')
      res.on('data', chunk => rawData += chunk)
      res.on('end', () => {
        try {
          resolve(JSON.parse(rawData))
        } catch (e) {
          console.error(e)
          resolve({})
        } finally {
          client.destroy()
        }
      })
      res.on('error', (e) => {
        console.error(e)
        resolve({})
      })
    })

    client.on('error', () => {
      console.error(e)
      resolve({})
    })
  })

const rendererArgs = {
  bundle: void 0,
  getManifest: async () => {
    if (await checkServer()) {
      return await getServerResources()
    } else {
      return getLocalResources()
    }
  }
}

serverComiler.outputFileSystem = mfc
serverComiler.watch({}, (err, status) => {
  if (err) throw err

  const data = status.toJson()

  data.errors.forEach(err => console.error(err))
  data.warnings.forEach(warn => console.warn(warn))

  rendererArgs.bundle = JSON.parse(mfc.readFileSync(bundlePath, 'utf-8'))

  console.log('vue-ssr-server-bundle generate')
})

module.exports = rendererArgs